package com.zzyl.service.impl;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.service.WeChatService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WechatServiceImpl implements WeChatService{
    private static final String getOpenIdUrl = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";
   private static final String getTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
    private static final String getPhoneNumberUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    @Override
    public String getOpenId(String code) {
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("appid", "wx8bc34a7f2f268e32");
        requestParams.put("secret", "622fd846c0aefeec39cb3d9cd18d73eb");
        requestParams.put("js_code", code);

        String result = HttpUtil.get(getOpenIdUrl, requestParams);

        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (ObjectUtil.isNotEmpty(jsonObject.getInt("errcode"))) {
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }
        return jsonObject.getStr("openid");
    }

    @Override
    public String getAccessToken() {
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("appid", "wx8bc34a7f2f268e32");
        requestParams.put("secret", "622fd846c0aefeec39cb3d9cd18d73eb");
        String token = HttpUtil.get(getTokenUrl,requestParams);
        JSONObject jsonObject = JSONUtil.parseObj(token);
        if(ObjectUtil.isNotEmpty(jsonObject.getInt("errcode"))){
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }
        return jsonObject.getStr("access_token");
    }

    @Override
    public String getPhoneNumber(String token, String code, String openId) {
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("code", code);

        String phoneNumber = HttpUtil.post(getPhoneNumberUrl+token,JSONUtil.toJsonStr(requestParams));
        JSONObject jsonObject = JSONUtil.parseObj(phoneNumber);
        if(jsonObject.getInt("errcode") != 0){
            System.out.println(jsonObject);
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }
        return jsonObject.getJSONObject("phone_info").getStr("purePhoneNumber");
    }
}
